// packageA/components/area-select/index.js
const WXAPI = require('../../../api/api')
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    isShowPop:{
      type:Boolean,
      value:true
    },
    isShow:{
      type:Boolean,
      value:false
    },
    isShowField:{
      type:Boolean,
      value:true
    },
    // 组件树回显地址对象
    areaInfoSelected: {
      type: Object,
      value: {}
    },
    // 传0-5  0 可选任意一级 1省级 2市级 3县区级 4街道/乡镇 5社区/村
    selectAreaLevelLimit: {
      type: Number,
      value: -1
    },
    // label标题
    label: {
      type: String,
      require: false
    },
    // 绑定标识
    name: {
      type: String,
      require: false
    },
    // 是否必填
    required: {
      type: Boolean,
      require: false,
      value: false
    },
    // true户籍地址 false常住地址
    isRegister: {
      type: Boolean,
      require: false,
      value: false
    },
    // 是否只读
    readonly: {
      type: Boolean,
      require: false,
      value: false
    },
    // 限制默认最小回显等级 0省级 1市级 2县区级 ；必须设置默认组件树回显地址对象areaInfoSelected或者isXiaMen
    defaultLimitArea: {
      type: Number,
      require: false,
      value: -1
    },
    // 回显数据时是否展示到回显地址的下一级(如true：需要回显的区划为：安徽省合肥市，则区划选择器中默认展示到区县一列)
    isCurrentLevelDisable: {
      type: Boolean,
      require: false,
      value: true
    },
    isSubmit: {
      type: Boolean,
      value: false
    }
  },
  // 监听传入的变量,当传入的值发生变化时,触发方法
  observers: {
    'areaInfoSelected': function (val) {
      // val=》就是父组件传入组件中的tabsList数据
      if (val.provinceObj.sCode) {
        this.getDefaultArea()
      }
    },
    'isShow': function (val) {
        this.setData({
          showAddressSelector: val
        })
    }
  },
  created(){
    this.getDefaultArea()
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      
    },
    hide: function () {},
    resize: function () {},
  },
  /**
   * 组件的初始数据
   */
  data: {
    showAddressSelector: false,
    areaFullName: '',
    currentLastLevel: 0,
    isLoading: false,
    showIndex: 0,
    state: {
      provinceObj: {},
      cityObj: {},
      areaObj: {},
      streetObj: {},
      villageObj: {},
      provinceData: [], // 省级
      cityData: [], // 市级
      areaData: [], //县区
      streetsData: [], //街道
      villagesData: [] // 村、社区
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    selectArea() {
      if (!this.properties.readonly) {
        this.setData({
          showAddressSelector: true
        })
      }
    },
    getDefaultArea() {
      if (
        this.properties.areaInfoSelected &&
        this.properties.areaInfoSelected.provinceObj &&
        this.properties.areaInfoSelected.provinceObj.sCode
      ) {
        let {
          provinceObj,
          cityObj,
          areaObj,
          streetObj,
          villageObj
        } = this.properties.areaInfoSelected
        this.setData({
          ['state.provinceObj']: provinceObj,
          ['state.cityObj']: cityObj,
          ['state.areaObj']: areaObj,
          ['state.streetObj']: streetObj,
          ['state.villageObj']: villageObj,
        })
        if (provinceObj.sCode && !cityObj.sCode) {
          this.handleGetMap(this.properties.areaInfoSelected.provinceObj, 'pro')
        }
        if (cityObj.sCode && !areaObj.sCode) {
          if (this.properties.isCurrentLevelDisable) {
            this.handleGetMap(this.properties.areaInfoSelected.cityObj, 'city')
          } else {
            this.handleGetMap(this.properties.areaInfoSelected.provinceObj, 'pro')
          }
        }
        if (areaObj.sCode && !streetObj.sCode) {
          if (this.properties.isCurrentLevelDisable) {
            this.handleGetMap(this.properties.areaInfoSelected.areaObj, 'area')
          } else {
            this.handleGetMap(this.properties.areaInfoSelected.cityObj, 'city')
          }
        }
        if (streetObj.sCode && !villageObj.sCode) {
          if (this.properties.isCurrentLevelDisable) {
            this.handleGetMap(this.properties.areaInfoSelected.streetObj, 'street')
          } else {
            this.handleGetMap(this.properties.areaInfoSelected.areaObj, 'area')
          }
        }
        if (villageObj.sCode) {
          this.handleGetMap(this.properties.areaInfoSelected.streetObj, 'street')
        }
        // 填充输入框地址全称
        this.setData({
          areaFullName: this.properties.areaInfoSelected.provinceObj.sName +
            this.properties.areaInfoSelected.cityObj.sName +
            this.properties.areaInfoSelected.areaObj.sName +
            this.properties.areaInfoSelected.streetObj.sName +
            this.properties.areaInfoSelected.villageObj.sName
        })
      } else {
        this.handleGetMap({}, 'init')
      }
    },
    closeAreaPop() {
      this.setData({
        showAddressSelector: false
      })
    },
    handleCancel() {
      this.setData({
        showAddressSelector: false
      })
      this.triggerEvent('cancelAddress')
    },
    handleSubmit() {
      const {
        provinceObj,
        cityObj,
        areaObj,
        streetObj,
        villageObj
      } = this.data.state
      const arr = [provinceObj, cityObj, areaObj, streetObj, villageObj]
      let fullAreaName = []
      arr.map(item => {
        if (item.sCode) {
          fullAreaName.push(item.sName)
        }
      })
      if (this.properties.selectAreaLevelLimit && this.properties.selectAreaLevelLimit != 0) {
        if (this.properties.selectAreaLevelLimit > 0) {
          if (fullAreaName.length < this.properties.selectAreaLevelLimit) {
            if (this.properties.selectAreaLevelLimit == 2) {
              wx.showToast({
                title: '地址需精确到市级！',
                icon: 'none'
              })
            }
            if (this.properties.selectAreaLevelLimit == 3) {
              wx.showToast({
                title: '地址需精确到县区级！',
                icon: 'none'
              })
            }
            if (this.properties.selectAreaLevelLimit == 4) {
              wx.showToast({
                title: '地址需精确到街道/乡镇级！',
                icon: 'none'
              })
            }
            if (this.properties.selectAreaLevelLimit == 5) {
              wx.showToast({
                title: '地址需精确到社区/村级！',
                icon: 'none'
              })
            }
            return
          }
        } else {
          // 限制必须选择到最后一级
          console.log('fullAreaName', fullAreaName)
          console.log('this.data.currentLastLevel',this.data.currentLastLevel);
          if (this.data.currentLastLevel != fullAreaName.length) {
            wx.showToast({
              title: '地址需精确最后一级！',
              icon: 'none'
            })
            return
          }
        }
      }
      let areaInfoObj
      if (this.properties.isRegister) {
        areaInfoObj = {
          obj: {
            registerProvince: provinceObj.sCode || '',
            registerCity: cityObj.sCode || '',
            registerCounty: areaObj.sCode || '',
            registerStreet: streetObj.sCode || '',
            registerCommunity: villageObj.sCode || '',
            registerProvinceName: provinceObj.sName || '',
            registerCityName: cityObj.sName || '',
            registerCountyName: areaObj.sName || '',
            registerStreetName: streetObj.sName || '',
            registerCommunityName: villageObj.sName || ''
          },
          defaultObj: {
            provinceObj,
            cityObj,
            areaObj,
            streetObj,
            villageObj
          },
          fullArea: fullAreaName.toString().replace(/,/g, '')
        }
      } else {
        areaInfoObj = {
          obj: {
            sProvinceCode: provinceObj.sCode || '',
            sCityCode: cityObj.sCode || '',
            sCountryCode: areaObj.sCode || '',
            sStreetCode: streetObj.sCode || '',
            sCommunityCode: villageObj.sCode || '',
            sProvinceName: provinceObj.sName || '',
            sCityName: cityObj.sName || '',
            sCountryName: areaObj.sName || '',
            sStreetName: streetObj.sName || '',
            sCommunityName: villageObj.sName || ''
          },
          defaultObj: {
            provinceObj,
            cityObj,
            areaObj,
            streetObj,
            villageObj
          },
          fullArea: fullAreaName.toString().replace(/,/g, '')
        }
      }
      console.log('areaInfoObj', areaInfoObj);
      this.setData({
        areaFullName: areaInfoObj.fullArea,
        showAddressSelector: false
      })
      this.triggerEvent('sureAddress', areaInfoObj)
    },
    //下拉选择
    newSelect(event) {
      console.log('event', event);
      let self = this
      let num = Number(event.currentTarget.dataset.id)
      switch (num) {
        case 0:
          console.log('self.properties.', self.properties);
          if (self.properties.defaultLimitArea >= 0) {
            return
          }
          self.setData({
            ['state.cityObj']: {},
            ['state.areaObj']: {},
            ['state.streetObj']: {},
            ['state.villageObj']: {},
            ['state.cityData']: [],
            ['state.areaData']: [],
            ['state.streetsData']: [],
            ['state.villagesData']: [],
            showIndex: 0
          })
          self.handleGetMap({}, 'init')
          break
        case 1:
          if (self.properties.defaultLimitArea >= 1) {
            return
          }
          self.setData({
            showIndex: 1,
            ['state.streetObj']: {},
            ['state.villageObj']: {},
            ['state.areaObj']: {},
            ['state.areaData']: [],
            ['state.streetsData']: [],
            ['state.villagesData']: [],
          })
          self.handleGetMap(self.data.state.provinceObj, 'pro')
          break
        case 2:
          if (self.properties.defaultLimitArea >= 2) {
            return
          }
          self.setData({
            showIndex: 2,
            ['state.streetObj']: {},
            ['state.villageObj']: {},
            ['state.streetsData']: [],
            ['state.villagesData']: [],
          })
          self.handleGetMap(self.data.state.cityObj, 'city')
          break
        case 3:
          if (self.properties.defaultLimitArea >= 3) {
            return
          }
          self.setData({
            showIndex: 3,
            ['state.villageObj']: {},
            ['state.villagesData']: [],
          })
          self.handleGetMap(self.data.state.areaObj, 'area')
          break
        case 4:
          if (self.properties.defaultLimitArea >= 4) {
            return
          }
          self.setData({
            showIndex: 4
          })
          self.handleGetMap(self.data.state.streetObj, 'street')
          break
        case 5:
          self.setData({
            showIndex: 5,
            ['state.villageObj']: {},
            ['state.villagesData']: [],
          })
          self.handleGetMap(self.data.state.villageObj, 'area')
          break
      }
    },
    handleGetMap(obj, type) {
      this.getAreaByCode(obj, type)
    },
    async getAreaByCode(obj, type) {
      console.log('obj', obj);
      console.log('type', type);
      // name选择名称 type类型
      let data = {
        parentArea: 0
      }
      if (type !== 'init') {
        data.parentArea = obj.sCode
        this.setData({
          isLoading: true
        })
      }
      let areaCode
      if (obj && obj.sCode) {
        areaCode = obj.sCode
      } else {
        areaCode = '000000'
      }
      // 每次请求带上parentArea 即可请求下一级区域数据
      let isCustomLoading = true
      let res = await WXAPI.getAreaListByCode(areaCode,isCustomLoading)
      console.log('res', res);
      if (res.data.code == 0) {
        let arr = ['init', 'pro', 'city', 'area', 'street']
        let _obj = {
          init: 'provinceData',
          pro: 'cityData',
          city: 'areaData',
          area: 'streetsData',
          street: 'villagesData'
        }
        let result = res.data.data.Childs
        this.setData({
          [`state.${[_obj[type]]}`]: result,
          showIndex: arr.indexOf(type),
          currentLastLevel: result && result.length > 0 ? result[0].iLevel : this.data.currentLastLevel,
          isLoading: false
        })
      } else {
        // isLoading.value = false
        // showSuccessToast(res.msg)
      }

    },
    handleSelectAddress(event) {
      console.log('event',event);
      let type = event.currentTarget.dataset.type
      let obj = event.currentTarget.dataset.item
      if (obj.disabled) {
        return
      }
      // if(obj.Childs.length == 0) {
      //     //选择最后一级
      //     this.setData({
      //       ['state.villageObj']: obj
      //     })
      //     return 
      // }
      switch (type) {
        case 0:
          //选择省
          this.handleGetMap(obj, 'pro')
          this.setData({
            ['state.provinceObj']: obj,
            ['state.cityData']: [],
            ['state.areaData']: [],
            ['state.streetsData']: [],
            ['state.villagesData']: [],
            showIndex: 1
          })

          break
        case 1:
          //选择市
          this.handleGetMap(obj, 'city')
          this.setData({
            ['state.cityObj']: obj,
            ['state.areaData']: [],
            ['state.streetsData']: [],
            ['state.villagesData']: [],
            showIndex: 2
          })


          break
        case 2:
          //选择区
          if (this.properties.selectAreaLevelLimit == 3) {
            // state.areaObj = obj
            this.setData({
              ['state.areaObj']: obj
            })
          } else {
            this.handleGetMap(obj, 'area')
            this.setData({
              ['state.areaObj']: obj,
              ['state.streetsData']: [],
              ['state.villagesData']: [],
              showIndex: 3
            })

          }
          break
        case 3:
          //选择街道
          if (this.properties.selectAreaLevelLimit == 4) {
            // state.streetObj = obj
            this.setData({
              ['state.streetObj']: obj
            })
          } else {
            this.handleGetMap(obj, 'street')
            this.setData({
              ['state.streetObj']: obj,
              ['state.villagesData']: [],
              showIndex: 4
            })

          }
          break
        case 4:
          //选择村、社区
          this.setData({
            ['state.villageObj']: obj
          })
          break
        default:
          break
      }
    }
  }
})